package ru.ifmo.itmokis.util;

import java.util.Enumeration;
import java.util.Properties;
import java.util.ResourceBundle;
import ru.ifmo.itmokis.domain.Time;
import ru.ifmo.itmokis.exceptions.ValueNotFoundException;

/**
 *
 * @author Ivan Stepuk
 */
public final class Config {

    public static String DEFAULT_CONFIG_FILE = "config";
    private ResourceBundle bundle;
    private Properties properties = new Properties();

    public Config() {
        this(DEFAULT_CONFIG_FILE);
    }

    public Config(String configFile) {
        bundle = ResourceBundle.getBundle(configFile);
        reloadFromFile();
    }

    public void reloadFromFile() {
        for (Enumeration<String> e = bundle.getKeys(); e.hasMoreElements();) {
            String key = e.nextElement();
            properties.put(key, bundle.getString(key));
        }
    }

    public int getInt(String key) {
        try {
            return Integer.parseInt(properties.getProperty(key));
        } catch (NumberFormatException ex) {
            throw new ValueNotFoundException(key);
        }
    }

    public void putInt(String key, int value) {
        properties.put(key, String.valueOf(value));
    }

    public double getDouble(String key) {
        try {
            return Double.parseDouble(properties.getProperty(key));
        } catch (NumberFormatException ex) {
            throw new ValueNotFoundException(key);
        }
    }

    public void putDouble(String key, double value) {
        properties.put(key, String.valueOf(value));
    }

    public String getString(String key) {
        return properties.getProperty(key);
    }

    public void putString(String key, String value) {
        properties.put(key, value);
    }

    public Time getTime(String key) {
        return new Time(getInt(key));
    }

    public void putTime(String key, Time value) {
        putInt(key, value.toPlainHours());
    }
}
